package com.baitiaojun.system.admin.service.permission.impl;

import com.baitiaojun.common.utils.string.StringUtils;
import com.baitiaojun.security.core.service.PermissionService;
import com.baitiaojun.system.admin.pojo.SysMenuDO;
import com.baitiaojun.system.admin.pojo.SysRoleDO;
import com.baitiaojun.system.admin.service.permission.AuthPermissionService;
import com.baitiaojun.system.admin.service.permission.MenuService;
import com.baitiaojun.system.admin.service.permission.RoleService;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class AuthPermissionServiceImpl implements AuthPermissionService {

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 根据用户id获取角色权限
     * @param userId
     * @return
     */
    @Override
    public Set<SysRoleDO> getRolesByUserId(String userId) {
        return roleService.getRolesByUserId(userId);
    }

    /**
     * 根据用户id获取菜单访问权限
     * @param userId
     * @param isAdmin
     * @return
     */
    @Override
    public Set<String> getPermsByUserId(String userId, boolean isAdmin) {
        if (isAdmin) {
            return Sets.newHashSet(permissionService.ALL_PERMISSION);
        }
        Set<SysMenuDO> menus = menuService.getPermsByUserId(userId);
        return menus.stream().filter(Objects::nonNull)
                .map(SysMenuDO::getPerms)
                .filter(StringUtils::isNotEmpty).collect(Collectors.toSet());
    }
}
